using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudentVideo.Common.Exceptions;
using StudentVideo.Shared.Models;

namespace StudentVideo.Filters;

public class CustomExceptionFilter(ILogger<HttpResultFilter> logger): IExceptionFilter {
   private readonly ILogger<HttpResultFilter> _logger = logger;

   public void OnException(ExceptionContext context) {
      // 在 Action 执行过程中发生异常时调用
      var result = new HttpResult<object> {
         StatusCode = 500,
         Message = "System Error",
         Data = null
      };

      if (context.Exception is HttpException) {
         result.Message = context.Exception.Message;
         _logger.LogError(
            "\n[Request Error] Path: {path}, ErrorMessage: {exception}",
            context.HttpContext.Request.Path,
            context.Exception.Message
         );
      } else {
         _logger.LogError(
            "\n[Request Error] Path: {path}, \nException: {exception}",
            context.HttpContext.Request.Path,
            context.Exception
         );
      }

      // 替换原始的返回结果
      context.Result = new ObjectResult(result) {
         StatusCode = 200
      };
   }
}
